using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemySpawner : MonoBehaviour {
	public GameObject prefabToSpawn;
	public GameObject player;
	public int spawnRemaining = 2;
	public float spawnSpeed = 0.5f;
	
	protected List<GameObject> spawns;
	protected float nextSpawnTime = 0f;
	
	// Use this for initialization
	void Start () {
		spawns = new List<GameObject>();
	}
	
	// Update is called once per frame
	void Update () {
		if (spawnRemaining > 0) {
			//Debug.Log (nextSpawnTime, this);
			if (Time.time > nextSpawnTime) {
				//Debug.Log ("SPAWWWWWN", this);
				Spawn();
				nextSpawnTime = Time.time + spawnSpeed;
			}
		}
		
		if (spawnRemaining == 0) {
			bool allSpawnsNull = true;
			foreach(GameObject spawn in spawns) {
				if (spawn != null) {
					allSpawnsNull = false;
				}
			}
		
			if (allSpawnsNull) {
				Die();
			}
		}
	}
	
	void Spawn() {
		//Create an instance of the loaded prefab
        GameObject enemyInstance = Instantiate(prefabToSpawn) as GameObject;
		
		// TODO: we assume that this is an Enemy! Bad assumption.
		enemyInstance.GetComponent<Enemy>().player = player;
		enemyInstance.transform.position = transform.position;
		enemyInstance.transform.rotation = transform.rotation;
		enemyInstance.transform.localScale = transform.localScale;
		
		spawns.Add(enemyInstance);
		
		spawnRemaining = spawnRemaining-1;
	}
	
	protected void Die()
    {
        Destroy(gameObject);
    }
}
